package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.githang.statusbar.StatusBarCompat;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.BrandInfoDB;
import com.ramos.kuaixiao.db.CustomerWareHouseDB;
import com.ramos.kuaixiao.db.PriceDB;
import com.ramos.kuaixiao.db.ShopsDB;
import com.ramos.kuaixiao.db.StoreNumDB;
import com.ramos.kuaixiao.db.WareHouseDB;
import com.ramos.kuaixiao.entity.BrandInfo;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.entity.Product;
import com.ramos.kuaixiao.entity.ShopTypeBean;
import com.ramos.kuaixiao.entity.WareHouse;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropSquareTransformation;

public class BrandInfoActivity extends BaseActivity implements View.OnClickListener {
    private static String TAG = "BrandInfoActivity";
    private Context mContext;
    private LinearLayout title_reback;
    private TextView title_text;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;

    /*android 图片点击一下就放大到全屏,再点一下就回到原界面 */
    SimpleDraweeView sdv_goods_img;
    String iconUrl;
    TextView tv_goods_title;
    TextView tv_barcode;
    TextView tv_code;
    TextView et_price;

    ImageView iv_assist_sub;
    ImageView iv_assist_plus;
    ImageView iv_sub;
    ImageView iv_plus;
    EditText et_assist_number;
    EditText et_number;
    TextView tv_cancel;
    TextView tv_add_to_cart;
    TextView tv_assist_unit;

    BrandInfo brand;
    ShopTypeBean.ShopType.ProductInfo productInfo;
    RadioGroup rg_inventory;
    String wareHouse;
    String productInfoId;
    String productBarCode;
    Customer customer;
    CustomerWareHouseDB wareHouseDB;
    int storeNum = 0;
    private List<Product.WareInfo> wareList = new ArrayList<>();
    String custmerId;
    String custmerName;
    String houseId;
    String houseName;
    ArrayList<String> datas = new ArrayList<>();
    WareHouseDB mWareHouseDB;
    List<WareHouse> mWareList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_brand_info);
        mContext = this;
        wareHouseDB = new CustomerWareHouseDB();
        mWareHouseDB = new WareHouseDB();
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        brand = new BrandInfo();
        initView();
        //initData();
    }

    private void initView() {
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("商品详情");

        sdv_goods_img = (SimpleDraweeView) findViewById(R.id.sdv_goods_img);
        sdv_goods_img.setOnClickListener(this);

        tv_goods_title = (TextView) findViewById(R.id.tv_goods_title);
        tv_barcode = (TextView) findViewById(R.id.tv_barcode);
        tv_code = (TextView) findViewById(R.id.tv_code);
        et_price = (TextView) findViewById(R.id.et_price);
        tv_assist_unit = (TextView) findViewById(R.id.tv_assist_unit);
        iv_assist_sub = (ImageView) findViewById(R.id.iv_assist_sub);
        iv_assist_plus = (ImageView) findViewById(R.id.iv_assist_plus);
        iv_sub = (ImageView) findViewById(R.id.iv_sub);
        iv_plus = (ImageView) findViewById(R.id.iv_plus);
        iv_assist_sub.setOnClickListener(this);
        iv_assist_plus.setOnClickListener(this);
        iv_sub.setOnClickListener(this);
        iv_plus.setOnClickListener(this);

        et_assist_number = (EditText) findViewById(R.id.et_assist_number);
        et_number = (EditText) findViewById(R.id.et_number);

        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        tv_add_to_cart = (TextView) findViewById(R.id.tv_add_to_cart);
        tv_cancel.setOnClickListener(this);
        tv_add_to_cart.setOnClickListener(this);

        rg_inventory = (RadioGroup) findViewById(R.id.rg_inventory);
        rg_inventory.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                RadioButton tempButton = (RadioButton) findViewById(checkedId); // 通过RadioGroup的findViewById方法，找到ID为checkedID的RadioButton
                // 以下就可以对这个RadioButton进行处理了
                tempButton.setSelected(true);
            }
        });

        productInfo = (ShopTypeBean.ShopType.ProductInfo) getIntent().getExtras().get("brand");
        customer = (Customer) getIntent().getExtras().get("customer");
        if (productInfo != null) {
            iconUrl = productInfo.getIconUrl();
            Glide.with(mContext).load(iconUrl).dontAnimate().bitmapTransform(new CropSquareTransformation(mContext)).diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(sdv_goods_img);
            datas.add(iconUrl);
            productInfoId = productInfo.getProductInfoId();
            productBarCode = productInfo.getProductBarCode();
            tv_goods_title.setText(productInfo.getProductInfoName());
            tv_barcode.setText("编码：" + productInfoId);
            tv_code.setText("条码：" + productBarCode);
            brand.setShop_Name(productInfo.getProductInfoName());
            brand.setEncode(productInfo.getProductInfoId());
            brand.setBarcode(productInfo.getProductBarCode());
            brand.setIcon(productInfo.getIconUrl());
            if (customer != null && !StringUtil.isEmpty(customer.getId())) {
                custmerId = customer.getId();
                custmerName = customer.getName();
                houseId = customer.getHouseId();
                houseName = customer.getHouseName();
            }
            /*if (StringUtil.isEmpty(new PriceDB().getPrice(productInfoId, customer.getQid())) || new StoreNumDB().getStoreNumList(productInfoId).size() == 0) {
                initData();
            } else {*/
            int param = new StoreNumDB().getParam(productInfoId);
            String singlePrice = App.df.format(Double.valueOf(productInfo.getNonTaxSalePrice()));
            double box = Double.valueOf(productInfo.getNonTaxSalePrice()) * Double.valueOf(param);
            String boxPrice = String.valueOf(App.df.format(box));
            et_price.setText(singlePrice + "元/支 " + boxPrice + "元/箱");
            tv_assist_unit.setText("箱(" + param + "支)");
            brand.setPrice(Double.valueOf(productInfo.getNonTaxSalePrice()));
            brand.setParam(Integer.valueOf(param));

            List<Product.WareInfo> tmp;
            if (!StringUtil.isEmpty(houseId) || !StringUtil.isEmpty(houseName))
                tmp = new StoreNumDB().getStores(productInfo.getProductInfoId(), houseId, houseName);
            else {
                tmp = new StoreNumDB().getStores(productInfo.getProductInfoId(), customer.getId(), custmerName);
            }
            Log.d("StoreNum", "tmp :" + tmp.size());
            if (tmp.size() > 0) {
                wareList.clear();
                wareList.addAll(tmp);
                addview(rg_inventory);
            } else {
                ToastUtils.show("暂无仓库信息，请确认商店仓库都已勾选！若勾选还是没有仓库信息，请查看其它商店");
            }
            /*}*/
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    Log.d(TAG, "result " + msg.obj.toString());
                    initShop(msg.obj.toString());
                    break;
                case UPLOAD_FAIL:
                    Log.d(TAG, "result fail");
                    //initShop("fail");
                    break;
                default:
                    break;
            }
        }
    };

    private void initShop(String s) {
        JSONObject jsonObejct = JSONObject.parseObject(s);
        JSONObject data = jsonObejct.getJSONObject("data");
        Product product = JSONObject.parseObject(data.toString(), Product.class);
        String singlePrice = product.getSalePrice();
        String boxPrice = String.valueOf(Double.valueOf(product.getSalePrice()) * Double.valueOf(product.getCalcParam()));
        et_price.setText(singlePrice + "元/支 " + boxPrice + "元/箱");
        tv_assist_unit.setText("箱(" + product.getCalcParam() + "支)");
        brand.setPrice(Double.valueOf(product.getSalePrice()));
        brand.setParam(Integer.valueOf(product.getCalcParam()));
        String ws;
        if (!StringUtil.isEmpty(houseId) || !StringUtil.isEmpty(houseName)) {
            ws = wareHouseDB.findCustomer(houseId + "", houseName + "");
        } else {
            ws = wareHouseDB.findCustomer(custmerId + "", custmerName + "");
        }
        mWareList = mWareHouseDB.findAllWareHouse(SharedPreference.getPreferString("org"));
        List<WareHouse> tmp;
        if (StringUtil.isEmpty(ws)) {
            tmp = mWareList;
        } else {
            tmp = Utils.getList(mWareList, Utils.strToSet(ws));
        }
        if (tmp.size() > 0) {
            wareList = Utils.getWare(new StoreNumDB().getStoreNumList(productInfoId), tmp);
            addview(rg_inventory);
        } else {
            ToastUtils.show("暂无仓库信息，请确认商店仓库都已勾选！");
        }
    }

    //动态添加视图
    public void addview(RadioGroup radiogroup) {
        for (int i = 0; i < wareList.size(); i++) {
            RadioButton tempButton = new RadioButton(this);
            tempButton.setBackgroundResource(R.drawable.radio_group_selector);   // 设置RadioButton的背景图片
            tempButton.setButtonDrawable(R.drawable.radio_group_selector);           // 设置按钮的样式
            tempButton.setPadding(30, 10, 30, 10);                 // 设置文字距离按钮四周的距离
            tempButton.setText(wareList.get(i).getWareHouseName() + getStore(wareList.get(i).getCount()));
            tempButton.setGravity(Gravity.CENTER);
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(700, 150);
            layoutParams.setMargins(10, 10, 10, 50);
            tempButton.setLayoutParams(layoutParams);
            radiogroup.addView(tempButton, layoutParams);
            if (i == 0) {
                radiogroup.check(tempButton.getId());
            }
        }
    }

    private String getStore(int count) {
        String store;
        int box = count / brand.getParam();
        int single = count % brand.getParam();
        Log.d(TAG, "getStore " + box + " " + single);
        store = "(" + box + "箱" + single + "支)";
        return store;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sdv_goods_img:
                showImage();
                break;
            case R.id.title_reback:
                finish();
                break;
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.iv_assist_sub:
                int num = Integer.valueOf(et_assist_number.getText().toString());
                if (num > 0) {
                    et_assist_number.setText(String.valueOf(--num));
                }
                break;
            case R.id.iv_assist_plus:
                int num1 = Integer.valueOf(et_assist_number.getText().toString());
                et_assist_number.setText(String.valueOf(++num1));
                break;
            case R.id.iv_sub:
                int num2 = Integer.valueOf(et_number.getText().toString());
                if (num2 > 0) {
                    et_number.setText(String.valueOf(--num2));
                }
                break;
            case R.id.iv_plus:
                int num3 = Integer.valueOf(et_number.getText().toString());
                et_number.setText(String.valueOf(++num3));
                break;
            case R.id.tv_add_to_cart:
                if (wareList.size() == 0 || wareList == null) {
                    ToastUtils.show("未找到仓库，无法下单");
                    return;
                }
                RadioButton radioButton = (RadioButton) findViewById(rg_inventory.getCheckedRadioButtonId());
                if (radioButton != null) {
                    int position = rg_inventory.indexOfChild(rg_inventory.findViewById(rg_inventory.getCheckedRadioButtonId()));
                    brand.setWarehouseId(wareList.get(position).getWareHouseId());
                    brand.setWarehouse(wareList.get(position).getWareHouseName());
                    brand.setStoreNum(wareList.get(position).getCount());
                    storeNum = wareList.get(position).getCount();
                    Log.d(TAG, "RadioButton " + wareList.get(position).getCount());
                }
                int box = Integer.valueOf(et_assist_number.getText().toString());
                int single = Integer.valueOf(et_number.getText().toString());

                //允许库存不足下单
                /*if (box * brand.getParam() + single > storeNum) {
                    ToastUtils.show("库存不足，请重新选择！");
                    return;
                }*/
                if (box == 0 && single == 0) {
                    ToastUtils.show("商品数量不能为空");
                } else {
                    brand.setCustomerId(custmerId);
                    brand.setCustomerName(custmerName);
                    brand.setHouseId(houseId);
                    brand.setHouseName(houseName);
                    brand.setNum_Box(box);
                    brand.setNum_Single(single);

                    int quantity;
                    if (single == 0) {
                        quantity = brand.getParam();
                    } else {
                        quantity = 1;
                    }

                   /* String unitSalePrice = new PriceDB().getUnitSalePrice(productInfoId);
                    if (StringUtil.isEmpty(unitSalePrice)) {
                        brand.setUnitSalePrice(Double.valueOf(productInfo.getNonTaxSalePrice()));
                    } else {
                        brand.setUnitSalePrice(Double.valueOf(unitSalePrice));
                    }*/

                    String unitSalePrice = productInfo.getNonTaxSalePrice();
                    brand.setUnitSalePrice(Double.valueOf(unitSalePrice));

                    brand.setUcti(brand.getUnitSalePrice() * quantity);

                    String notexPrice = new PriceDB().getNotexSalePrice(productInfoId,custmerId);

                    if (Double.valueOf(notexPrice) == 0.0) {
                        brand.setUcte(Double.valueOf(productInfo.getNonTaxSalePrice()) / ((100 + productInfo.getTaxrate()) / 100) * quantity);
                    } else {
                        brand.setUcte(Double.valueOf(notexPrice) * quantity);
                    }

                    brand.setSalePriceT4(brand.getUnitSalePrice());
                    brand.setRealUcti(brand.getUcti());
                    brand.setRealUcte(brand.getUcte());
                    if (box != 0 && single != 0) {
                        brand.setTcti(brand.getUcti() * (box * brand.getParam() + single));
                        brand.setTcte(brand.getUcte() * (box * brand.getParam() + single));
                    } else if (box != 0 && single == 0) {
                        brand.setTcti(brand.getUcti() * box);
                        brand.setTcte(brand.getUcte() * box);
                    } else if (box == 0 && single != 0) {
                        brand.setTcti(brand.getUcti() * single);
                        brand.setTcte(brand.getUcte() * single);
                    }
                    //brand.setTaxRate(17);
                    brand.setTaxRate(Double.valueOf(new ShopsDB().getTaxRate(productInfoId)));
                    //brand.setTaxAmount(brand.getUcti() - brand.getUcte());
                    brand.setTaxAmount(brand.getTcti() - brand.getTcte());
                    brand.setInitPrice(Double.valueOf(productInfo.getNonTaxSalePrice()));
                    brand.setAddress(customer.getCity() + customer.getAddress());
                    brand.setTelphone(customer.getTelephone());
                    BrandInfoDB user = new BrandInfoDB();
                    Log.d(TAG, "brand :getPrice " + brand.getPrice() + " notexPrice:"+notexPrice + " setUcte" +brand.getUcte() + " " + new ShopsDB().getTaxRate(productInfoId) );
                    int i = user.addShop(brand);
                    if (i == 0) {
                        ToastUtils.show("已添加到购物车");
                        finish();
                    } else if (i == 1) {
                        ToastUtils.show("已更新到购物车");
                        finish();
                    } else if (i == -1) {
                        /*ToastUtils.show("库存不足，请修改订单数量");
                        finish();*/
                    } /*else if (i == 2) {
                        final SelfDialog builder = new SelfDialog(mContext);
                        builder.setTitle("购物车");
                        builder.setMessage("已存在其它商店的商品，继续添加会删除已存在商品，是否继续添加？");
                        builder.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                            @Override
                            public void onNoClick() {
                                builder.dismiss();
                            }
                        });
                        builder.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                BrandInfoDB user = new BrandInfoDB();
                                user.deleteAllShop();
                                int i = user.addShop(brand);
                                if (i == 0) {
                                    ToastUtils.show("已添加到购物车");
                                    finish();
                                } else {
                                    ToastUtils.show("添加失败");
                                }
                                builder.dismiss();
                            }
                        });
                        builder.show();
                    }*/
                }
                break;
            default:
                break;
        }
    }

    private void showImage() {
        Intent intent = new Intent(this, SpaceImageDetailActivity.class);
        intent.putExtra("images", iconUrl);
        int[] location = new int[2];
        sdv_goods_img.getLocationOnScreen(location);
        intent.putExtra("locationX", location[0]);
        intent.putExtra("locationY", location[1]);

        intent.putExtra("width", sdv_goods_img.getWidth());
        intent.putExtra("height", sdv_goods_img.getHeight());
        startActivity(intent);
        overridePendingTransition(0, 0);
    }
}
